#!/usr/bin/env node

require('dotenv').config();
const { Client } = require('basic-ftp');
const chalk = require('chalk');

async function fixedTest() {
    console.log(chalk.blue('🔧 修复版FTP连接测试'));
    
    const client = new Client();
    client.ftp.verbose = true;
    client.ftp.timeout = 30000;
    
    // 关键修复：禁用UTF8选项
    const originalAccess = client.access.bind(client);
    client.access = async function(config) {
        // 临时禁用UTF8相关命令
        const originalSendCommand = this.ftp.socket && this.ftp.socket.write ? this.ftp.socket.write.bind(this.ftp.socket) : null;
        
        try {
            // 先建立连接但不发送UTF8命令
            await originalAccess.call(this, config);
            return;
        } catch (error) {
            throw error;
        }
    };

    try {
        console.log(chalk.yellow('使用修复版连接...'));
        
        // 手动实现连接逻辑
        const net = require('net');
        const socket = new net.Socket();
        
        await new Promise((resolve, reject) => {
            socket.connect(parseInt(process.env.FTP_PORT) || 21, process.env.FTP_HOST, () => {
                console.log(chalk.green('✅ Socket连接成功'));
                resolve();
            });
            
            socket.on('error', reject);
            socket.setTimeout(10000, () => reject(new Error('连接超时')));
        });

        // 手动处理FTP认证
        await new Promise((resolve, reject) => {
            let buffer = '';
            let step = 0;
            
            socket.on('data', (data) => {
                buffer += data.toString();
                const lines = buffer.split('\r\n');
                
                for (let i = 0; i < lines.length - 1; i++) {
                    const line = lines[i];
                    console.log(chalk.gray('< ' + line));
                    
                    if (step === 0 && line.startsWith('220')) {
                        // 发送用户名
                        console.log(chalk.cyan(`> USER ${process.env.FTP_USER}`));
                        socket.write(`USER ${process.env.FTP_USER}\r\n`);
                        step = 1;
                    } else if (step === 1 && line.startsWith('331')) {
                        // 发送密码
                        console.log(chalk.cyan('> PASS ****'));
                        socket.write(`PASS ${process.env.FTP_PASSWORD}\r\n`);
                        step = 2;
                    } else if (step === 2 && line.startsWith('230')) {
                        console.log(chalk.green('✅ 认证成功'));
                        resolve();
                        return;
                    } else if (line.startsWith('530') || line.startsWith('421')) {
                        reject(new Error('认证失败: ' + line));
                        return;
                    }
                }
                
                buffer = lines[lines.length - 1];
            });
            
            socket.on('error', reject);
            setTimeout(() => reject(new Error('认证超时')), 10000);
        });
        
        socket.end();
        console.log(chalk.green('✅ 修复版连接测试成功！'));
        
    } catch (error) {
        console.error(chalk.red('❌ 修复版测试失败:'), error.message);
    }
}

fixedTest();